/*
 * @Author: xinyang3
 * @Date: 2021-10-09 14:32
 * @Descripttion: blog-doc router
 * @LastEditors: xinyang3
 * @LastEditTime: 2021-10-12 15:15
 */
import router from './router';
import { saveFileAsync, deleteFileAsync } from '../util/doc-file';
import url_prifix from '/bgmg/blog-doc';
import CollectionBlogDoc from '../collection/blog-doc';
import parsenFile from './show-md';

function stringify(result) {
  return JSON.stringify({
    type: 'succss',
    state: 200,
    data: result
  });
}

router.post(`${url_prifix}/insert`, async ({ request, response }, next) => {
  const data = request.body;
  const file = request.files.file;

  const filedata = await saveFileAsync(file);
  // 保存文件
  const result = await CollectionBlogDoc.insertOne({
    ...data,
    ...filedata
  });

  response.body = stringify(result);
});

router.post(`${url_prifix}/update`, async ({ request, response }, next) => {
  const data = ({ _id, state, user, file_name } = request.body);
  const file = request.files.file;

  // 保存文件
  const bolean = await deleteFileAsync({ file_name });
  const filedata = await saveFileAsync(file);

  const result = await CollectionBlogDoc.updateOne({
    _id,
    state,
    user,
    ...filedata
  });
  response.body = stringify(result);
});

router.get(`${url_prifix}/list`, async ({ request, response }, next) => {
  const query = request.query;
  const result = await CollectionBlogDoc.query(query);
  response.body = stringify(result);
});

// 获取md文件并转换成html字符串
router.get(`${url_prifix}/detail/:name`, async function(
  { request, response },
  next
) {
  const { _id, blog_doc_id } = request.query;

  const colect = await CollectionBlogDoc.queryOne({ _id: blog_doc_id });

  let data = null;
  if (colect && colect.file_name) {
    data = await parsenFile(colect.file_name);
  } else {
    data = '记录不存在.';
  }

  response.body = JSON.stringify({
    type: 'success',
    state: 200,
    data: data
  });
});

router.delete(
  `${url_prifix}/deleteOne`,
  async ({ request, response }, next) => {
    const { file_name, _id } = (query = request.query);
    const bolean = await deleteFileAsync({ file_name });
    const result = await CollectionBlogDoc.deleteOne(query);
    response.body = stringify(result);
  }
);
